package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.DatePicker.DatePicker;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.BirthdayBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.HeadPortraitBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.InformationBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.tool.GlideCircleTransform;
import com.hangzhou.welbeing.welbeinginstrument.utils.BitmapcCrcular;
import com.hangzhou.welbeing.welbeinginstrument.utils.GlideImageLoader;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 09 月 14.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 * @DESC 个人信息
 */
public class PersonalInformationActivity extends Activity {
    private static final String TAG = "TAG";
    @Bind(R.id.activity_personal_information_iv_return)
    ImageView activityPersonalInformationIvReturn;
    @Bind(R.id.activity_personal_information_rl_head_portrait)
    RelativeLayout activityPersonalInformationRlHeadPortrait;
    @Bind(R.id.activity_personal_information_rl_nickname)
    RelativeLayout activityPersonalInformationRlNickname;
    @Bind(R.id.activity_personal_information_rl_birthday)
    RelativeLayout activityPersonalInformationRlBirthday;
    @Bind(R.id.activity_personal_information_rl_individuality_signature)
    RelativeLayout activityPersonalInformationRlIndividualitySignature;


    @Bind(R.id.activity_personal_information_iv_head_portrait)
    ImageView activityPersonalInformationIvHeadPortrait;
    @Bind(R.id.activity_personal_information_tv_name)
    TextView activityPersonalInformationTvName;

    @Bind(R.id.activity_personal_information_tv_birthday)
    TextView activityPersonalInformationTvBirthday;


    @Bind(R.id.activity_personal_information_rl_personal_homepage_background)
    RelativeLayout activityPersonalInformationRlPersonalHomepageBackground;
    @Bind(R.id.activity_personal_information_iv_personal_homepage_background)
    ImageView activityPersonalInformationIvPersonalHomepageBackground;

    private Bitmap head;//头像Bitmap
    private static String path = "/sdcard/DemoHead/";//sd路径
    private String confirmNickname;

    private Calendar calendar = Calendar.getInstance();
    private int state = 1;
    private ImagePicker imagePicker;
    ArrayList<ImageItem> images = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_information);
        ButterKnife.bind(this);

        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader()); //TODO 设置图片加载器
        imagePicker.setMultiMode(false); // TODO 单选
        imagePicker.setShowCamera(true);  //TODO 显示相机 显示拍照按钮
        imagePicker.setSaveRectangle(true); //TODO 是否按矩形区域保存图片
        // TODO 设置图片保存宽高 保存文件的宽高
        imagePicker.setOutPutX(800);
        imagePicker.setOutPutY(800);

        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String cus_name = sp.getString("cus_name","");
        String birthday = sp.getString("birthday","");
        String cus_logo = sp.getString("cus_logo","");
        activityPersonalInformationTvName.setText(cus_name);

        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd");
        activityPersonalInformationTvBirthday.setText(time.format(new Date()));
        Glide.with(this).load(RBConstants.SERVER_URL+"/Public/Uploads/"+cus_logo).transform(new GlideCircleTransform(this)).into(activityPersonalInformationIvHeadPortrait);



    }

    @OnClick({R.id.activity_personal_information_iv_return, R.id.activity_personal_information_rl_head_portrait,
            R.id.activity_personal_information_rl_nickname, R.id.activity_personal_information_rl_birthday,
            R.id.activity_personal_information_rl_individuality_signature,R.id.activity_personal_information_rl_personal_homepage_background})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_personal_information_iv_return:
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                break;
            case R.id.activity_personal_information_rl_head_portrait: //更改头像
//                state = 1;
//                LlHeadPortrait();
                changePicture();
                break;
            case R.id.activity_personal_information_rl_nickname:
                Intent intent = new Intent(PersonalInformationActivity.this, NicknameActivity.class);
                startActivityForResult(intent,5);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                break;
            case R.id.activity_personal_information_rl_birthday:
                Birthday();
                break;
            case R.id.activity_personal_information_rl_individuality_signature:
                Intent intent1 = new Intent(PersonalInformationActivity.this, IndividualitySignatureActivity.class);
                startActivity(intent1);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                break;
            case R.id.activity_personal_information_rl_personal_homepage_background:
                state = 2;
                LlHeadPortrait();
            break;
        }
    }
    /**
     * @desc 更改头像
     * */
    private void changePicture() {
        //TODO 开启相册
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
        //ImagePicker.getInstance().setSelectedImages(images);
        startActivityForResult(intent, 100);
    }

    /**
     * @desc 生日
     * */
    private void Birthday() {
        DatePicker picker = new DatePicker(this);
        picker.setRange(2000, 2030);
        picker.setSelectedItem(calendar.get(calendar.YEAR), calendar.get(calendar.MONTH) + 1, calendar.get(calendar.DAY_OF_MONTH));
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                activityPersonalInformationTvBirthday.setText(year + "-" + month + "-" + day);
                Log.e(TAG,year + "-" + month + "-" + day);
                SharedPreferences sp1 = getSharedPreferences("release_cache_data", 0);
                SharedPreferences.Editor edit1 = sp1.edit();
                edit1.putString("is_login_return_birthday",year + "-" + month + "-" + day);
                edit1.commit();
                changeBirthdayData(year + "-" + month + "-" + day);
            }
        });
        picker.show();
    }
    /***
     * @desc 修改生日
     * @param birthday
     * */
    private void changeBirthdayData(final String birthday ) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id", "");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CHANGE_BIRTHDAY)
                .addParams("cus_id",user_id)
                .addParams("birthday", birthday)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String stringparseNetworkResponse = response.body().string();
                        Gson gson = new Gson();
                        //Log.e(TAG,"stringparseNetworkResponse----Birthday---9------->"+stringparseNetworkResponse);
                        final BirthdayBean birthdayBean =   gson.fromJson(stringparseNetworkResponse,BirthdayBean.class);
                        if(birthdayBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(PersonalInformationActivity.this,"生日已提交",Toast.LENGTH_SHORT).show();
                                    activityPersonalInformationTvBirthday.setText(birthday);
                                    SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("birthday",birthday);
                                    edit.commit();
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(PersonalInformationActivity.this,birthdayBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @desc 弹出选项框供用户选择
     * @desc 选项框有从相册中选择 拍照  取消 上传头像
     * */
    private void LlHeadPortrait() {
        new AlertView("上传头像", null, "取消", null, new String[]{"拍照", "从相册中选择"}, this, AlertView.Style.ActionSheet, new OnItemClickListener(){
            public void onItemClick(Object o,int position){
                // Toast.makeText(PersonalInformationActivity.this, "点击了第" + position + "》》》》》》个", Toast.LENGTH_SHORT).show();
                /**
                 * @desc 拍照是 0
                 * @desc 从相册中选择 1
                 * @desc 取消 -1
                 * */
                if(position == -1){  //取消 -1

                }else if(position == 0){  //拍照是 0
                    //最好用try/catch包裹一下，防止因为用户未给应用程序开启相机权限，而使程序崩溃
                    try {
                        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//开启相机应用程序获取并返回图片（capture：俘获）
                        intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                "head.jpg")));//指明存储图片或视频的地址URI
                        startActivityForResult(intent2, 2);//采用ForResult打开
                    } catch (Exception e) {
                        Toast.makeText(PersonalInformationActivity.this, "相机无法启动，请先开启相机权限", Toast.LENGTH_LONG).show();
                    }
                }else if(position == 1){  //从相册中选择 1
                    Intent intent6 = new Intent(Intent.ACTION_PICK, null);//返回被选中项的URI
                    intent6.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");//得到所有图片的URI
                    startActivityForResult(intent6, 1);
                }

            }
        }).show();
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //从相册里面取相片的返回结果
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());//裁剪图片
                }
                break;
            //相机拍照后的返回结果
            case 2:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));//裁剪图片
                }
                break;
            //调用系统裁剪图片后
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    Log.e(TAG, "setPicToView----------%%%%---->" + head);
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        activityPersonalInformationIvHeadPortrait.setImageBitmap(BitmapcCrcular.makeRoundCorner(head));//用ImageView显示出来
                       // setPicToView(head);//保存在SD卡中
                    }
                }
                break;
            case 4:
                if (data != null) {
                    confirmNickname = data.getStringExtra("confirmNickname");
                    if (confirmNickname == null) {
                        confirmNickname = "麻麻";
                    }
                    //tv_01.setText(confirmNickname);
                }
                break;
            case 5:
                String cus_name = data.getStringExtra("cus_name");
                activityPersonalInformationTvName.setText(cus_name);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                Log.e(TAG, "setPicToView--------3333---->" + images.get(0).path);
                //imagePicker.getImageLoader().displayImage(this, images.get(0).path, activityPersonalInformationIvHeadPortrait, 60, 60);
                activityPersonalInformationIvHeadPortrait.setImageBitmap(BitmapcCrcular.makeRoundCorner(BitmapFactory.decodeFile(images.get(0).path)));//将图片的长和宽缩小味原来的1/2
                SubmiheadPortrait(new File(images.get(0).path));
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //找到指定URI对应的资源图片
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        //进入系统裁剪图片的界面
        startActivityForResult(intent, 3);
    }
    private void setPicToView(Bitmap mBitmap) {
        Log.e(TAG,"setPicToView----------%%%%---->");
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd卡是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建以此File对象为名（path）的文件夹
        String fileName = path + "head.jpg";//图片名字
        try {
            b = new FileOutputStream(fileName);
            Log.e(TAG,"setPicToView-------------->"+fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件（compress：压缩）
            SubmiheadPortrait(new File(fileName));
        } catch (FileNotFoundException e) {
        } finally {
            try {
                //关闭流
                if(b != null){
                    b.flush();
                    b.close();
                }
            } catch (IOException e) {
            }

        }
    }
    /***
     * @desc  提交个人主页背景
     * */
    private void submitpersonalHomepageBackground(File file) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id", "");
        OkHttpUtils.post()//
                .addFile("", "head.jpg", file)//
                .url(RBConstants.SERVER_URL)
                .addParams("cus_id", user_id)
                .build()//
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String stringparseNetworkResponse = response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"stringparseNetworkResponse----setPicToView---9------->"+stringparseNetworkResponse);
                        final HeadPortraitBean headPortraitBean =  gson.fromJson(stringparseNetworkResponse,HeadPortraitBean.class);
                        if(headPortraitBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(PersonalInformationActivity.this,"个人主页背景上传成功",Toast.LENGTH_SHORT).show();
                                    EventBus.getDefault().post(new InformationBean("PersonalInformationActivity",headPortraitBean.data.cus_logo));

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(PersonalInformationActivity.this,headPortraitBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * desc 上传头像
     * */
    private void SubmiheadPortrait(File file) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id", "");
        OkHttpUtils.post()//
                .addFile("cus_logo", "head.jpg", file)//
                .url(RBConstants.SERVER_URL+RBConstants.UPLOAD_PICTURE)
                .addParams("cus_id", user_id)
                .build()//
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String stringparseNetworkResponse = response.body().string();
                        Gson gson = new Gson();
                       Log.e(TAG,"stringparseNetworkResponse----setPicToView---9------->"+stringparseNetworkResponse);
                        final HeadPortraitBean headPortraitBean =  gson.fromJson(stringparseNetworkResponse,HeadPortraitBean.class);
                        if(headPortraitBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(PersonalInformationActivity.this,"头像设置成功",Toast.LENGTH_SHORT).show();
                                    EventBus.getDefault().post(new InformationBean("PersonalInformationActivity",headPortraitBean.data.cus_logo));
                                    SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("cus_logo",headPortraitBean.data.cus_logo); //loginBean.data.id
                                    edit.commit();

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(PersonalInformationActivity.this,headPortraitBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
}
